import {
  getAllClassify
} from '../../api/index'
Page({
  data: {
    loading: true,
    activeTab: 0,
    classifyList: [],
  },
  $data: {
    selectedItem: []
  },
  onLoad: function (options) {
    let data = JSON.parse(options.list)

    getAllClassify().then(res => {
      let serverData = res.data
      this.setData({
        loading: false
      })
      this.init(data, serverData)
    })
  },

  // 初始选中值,初始所有选项值
  init(data, serverData) {
    this.$data.selectedItem = data
    // 初始化设置选中值高亮
    serverData.forEach(classifys => {
      classifys.checkedNum = 0
      classifys.classifyList.forEach(classify => {
        if (data.indexOf(classify.name) === -1) {
          classify.checked = false
        } else {
          classify.checked = true
          classifys.checkedNum++
        }
      })
    })

    console.log(serverData)
    this.setData({
      classifyList: serverData
    })
  },

  onChangeTabs(e) {
    const activeTab = e.detail.activeKey
    this.setData({
      activeTab
    })
  },

  clickItem(e) {
    const index = e.currentTarget.dataset.index
    const {
      classifyList,
      activeTab
    } = this.data
    const {
      selectedItem
    } = this.$data
    const classifys = classifyList[activeTab]
    const classify = classifys.classifyList[index];
    classify.checked = !classify.checked;

    if (classify.checked) {
      selectedItem.push(classify.name)
      classifys.checkedNum++
    } else {
      const index = selectedItem.indexOf(classify.name)
      if (index !== -1) {
        selectedItem.splice(index, 1)
        classifys.checkedNum--
      }
    }

    this.setData({
      classifyList
    });
  },

  confirm() {
    const pages = getCurrentPages()
    const prePage = pages[pages.length - 2] //上一个页面
    prePage.setData({
      classifyList: this.$data.selectedItem
    })
    wx.navigateBack({
      delta: 1,
    })
  },
})